package cn.zl.ymcc.service.impl;

import cn.zl.ymcc.constant.CodeConstant;
import cn.zl.ymcc.dto.CodeDto;
import cn.zl.ymcc.exception.GlobalBusinessException;
import cn.zl.ymcc.service.RefryCodeService;
import cn.zl.ymcc.utils.PhoneValidator;
import cn.zl.ymcc.utils.SendSmsVerifyCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class RefryCodeServiceImpl implements RefryCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sendCode(String phone) {
       if (!PhoneValidator.validateBasic(phone)){
           throw new GlobalBusinessException("手机号格式错误");
       }
        CodeDto codeDto=null;
         codeDto = (CodeDto) redisTemplate.opsForValue().get(CodeConstant.PHONE_CODE_KEY + phone);
         if(codeDto!=null){
             Long codeTimer = codeDto.getTimer();
             long nowTime = System.currentTimeMillis();
             if (nowTime - codeTimer < 60000) {
                 throw new GlobalBusinessException("请勿重复发送验证码");
             }

         }else {
             codeDto = new CodeDto(
                     String.valueOf((int) (Math.random() * 10000)),
                     System.currentTimeMillis());

         }
        SendSmsVerifyCode.sendSmsVerifyCode(phone, codeDto.getCode());
        redisTemplate.opsForValue().set(
                CodeConstant.PHONE_CODE_KEY + phone,
                codeDto,
                5,
                TimeUnit.MINUTES);
       codeDto = (CodeDto) redisTemplate.opsForValue().get(CodeConstant.PHONE_CODE_KEY + phone);
      log.info("验证码："+codeDto.getCode()+"发送时间："+codeDto.getTimer());
    }
}
